<template>
  <div>
    <!-- <div class="grid-content bg-purple-light" />
        <div class="dataTitle"><i class="el-icon-office-building" style="padding:20px" />数据字典</div>-->
    <div class="box-header box">
      <el-card>
        <el-page-header
          :title="$t('common.back')"
          :content="$t('modules.contract.detail_contract')"
          style="margin-bottom: 20px"
          @back="back"
        />
        <!-- 合同详情 -->
        <div style="font-size: 18px; margin: 0px 0px 20px 10px">
          <span
            style="
              display: inline-block;
              height: 30px;
              border-left: 4px solid #2569c3;
              text-indent: 10px;
            "
            >{{ $t("modules.contract.basic") }}
          </span>
          <el-button type="primary" style="float: right" @click="goToDetail">
            {{ $t("modules.contract.contract_edit") }}
          </el-button>
          <el-button
            v-if="contractData.status === 1 && isAuth('10401000.MANAGE')"
            type="danger"
            style="float: right; margin-right: 10px"
            @click="ContractInvalid"
          >
            {{ $t("modules.contract.status_option[0].label") }}
          </el-button>
          <el-button
            v-if="contractData.status === 0"
            type="success"
            style="float: right; margin-right: 10px"
            @click="ContractValid"
          >
            {{ $t("modules.contract.status_option[1].label") }}
          </el-button>
        </div>
        <el-form
          ref="contractData"
          v-loading.fullscreen.lock="loading"
          :model="contractData"
          label-width="150px"
        >
          <el-row class="flexContract">
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item
                :label="$t('common.customer_name')"
                class="item"
                prop="userName"
              >
                <el-input
                  ref="name"
                  v-model="contractData.userName"
                  disabled
                  clearable
                  style="width: 100%"
                  @focus="getKeyId($event)"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item
                class="item"
                :label="$t('modules.contract.contract_no')"
                prop="contractNum"
                style="width: 100%"
              >
                <el-input
                  v-model="contractData.contractNum"
                  disabled
                  maxlength="32"
                  show-word-limit
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="flexContract">
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item
                class="item"
                :label="$t('common.startDate')"
                prop="contractDate"
              >
                <el-date-picker
                  v-model="contractData.effectiveDate"
                  disabled
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYYMMDD"
                  range-separator="-"
                  :start-placeholder="$t('common.start_time')"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item
                class="item"
                :label="$t('modules.contract.sign_entity_id')"
                prop="signEntityId"
                style="width: 100%"
              >
                <el-input
                  v-model="contractData.signEntityName"
                  disabled
                  maxlength="32"
                  show-word-limit
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="email">
            <template #label>
              <span>
                <div style="margin-bottom: -20px">
                  {{ $t("flycare.contract.fixed_notify_email") }}
                  <el-tooltip placement="top">
                    <template #content>
                      <div>
                        {{ $t("modules.contract.email_hint") }}
                      </div></template
                    >
                    <i class="el-icon-warning" style="font-size: 2px" />
                  </el-tooltip>
                </div> </span
            ></template>
            <!--            <el-input-->
            <!--              v-model="fixedEmail"-->
            <!--              style="display: inline-block"-->
            <!--              -->
            <!--              type="textarea"-->
            <!--              maxlength="1000"-->
            <!--              disabled-->
            <!--            />-->
            <label>{{ fixedEmail }}</label>
          </el-form-item>
          <el-form-item prop="email">
            <template #label>
              <span>
                <div style="margin-bottom: -20px">
                  {{ $t("modules.contract.email") }}
                  <el-tooltip placement="top">
                    <template #content>
                      <div>
                        {{ $t("modules.contract.email_hint") }}
                      </div></template
                    >
                    <i class="el-icon-warning" style="font-size: 2px" />
                  </el-tooltip>
                </div> </span
            ></template>
            <el-input
              v-model="contractData.email"
              style="display: inline-block"
              disabled
              type="textarea"
              maxlength="1000"
              rows="2"
            />
          </el-form-item>
          <el-form-item
            :label="$t('modules.contract.remark')"
            style="margin-bottom: 20px"
          >
            <el-input
              v-model="contractData.remark"
              disabled
              maxlength="500"
              type="textarea"
              rows="2"
            />
          </el-form-item>
          <!-- 合同模块详情 -->
          <div style="font-size: 18px; margin: 0px 0px 20px 10px">
            <span
              style="
                display: inline-block;
                height: 30px;
                border-left: 4px solid #2569c3;
                text-indent: 10px;
              "
              >{{ $t("modules.contract.modules_title") }}</span
            >
          </div>
          <template>
            <div
              class="selectColumn"
              :class="multipleSelection.length > 0 ? 'active' : ''"
            >
              <span class="selectSpan">{{ invalidCount }}</span>
              <span class="selectSpan" style="">{{ $t("modules.contract.select") }}</span>
              <span class="selectBorder" />
              <el-button
                v-permission="{ permission: '10401000.MANAGE' }"
                :disabled="!(multipleSelection.length > 0)"
                style="margin-left: 20px; padding: 5px 5px"
                type="buttion"
                :class="multipleSelection.length > 0 ? 'buttonInvalid' : ''"
                @click="invalidModules"
                ><svg-icon icon-class="lock" class="text-lg" />
                {{ $t("modules.contract.invalidate") }}</el-button
              >
            </div>
            <el-table
              :data="moduleData"
              style="width: 100%; margin-left: 0px"
              @selection-change="handleSelectionChange"
            >
              <template #empty>
                <el-empty :image-size="100" description="No data" />
              </template>
              <el-table-column type="selection" :selectable="selected" width="55" />
              <!--              <el-table-column prop="platCode" :label="$t('modules.contract.plat')" width="100px">-->
              <!--                <template v-slot="scope">-->
              <!--                  <span>{{ $t('contract_plat.' + scope.row.platCode) }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column
                prop="billingServiceCode"
                :label="$t('modules.contract.billing_method')"
                width="220"
              >
                <template v-slot="scope">
                  <p>{{ $t("contract_plat." + scope.row.platCode) }}</p>
                  <p>
                    {{
                      $t(
                        "flycare.billing_service." +
                          scope.row.billingServiceCode +
                          ".name"
                      )
                    }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column :label="'Billing mode'">
                <template v-slot="scope">
                  <p v-if="scope.row.serviceAmount">
                    {{
                      "$" +
                      Number(scope.row.serviceAmount).toLocaleString() +
                      (scope.row.serviceQuantity
                        ? " for " +
                          Number(scope.row.serviceQuantity).toLocaleString() +
                          " " +
                          $t(
                            "flycare.billing_service." +
                              scope.row.billingServiceCode +
                              ".quantity_unit"
                          )
                        : "")
                    }}
                  </p>
                  <p v-if="scope.row.price">
                    {{
                      Number(scope.row.price).toLocaleString() +
                      " " +
                      $t(
                        "flycare.billing_service." +
                          scope.row.billingServiceCode +
                          ".price_unit"
                      )
                    }}
                  </p>
                  <p v-if="scope.row.freeNum">
                    {{
                      Number(scope.row.freeNum).toLocaleString() +
                      " " +
                      $t(
                        "flycare.billing_service." +
                          scope.row.billingServiceCode +
                          ".quantity_unit"
                      ) +
                      " for free " +
                      (scope.row.freeExpireTime
                        ? "(Expire: " + formatToMonth(scope.row.freeExpireTime) + ")"
                        : "")
                    }}
                  </p>
                </template>
              </el-table-column>
              <!--              <el-table-column-->
              <!--                :label="$t('modules.contract.service_quantity')"-->
              <!--                -->
              <!--              >-->
              <!--                <template v-slot="scope">-->
              <!--                  <span>{{ scope.row.serviceQuantity ? Number(scope.row.serviceQuantity).toLocaleString() : '-' }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column :label="$t('modules.contract.valid_period')">
                <template v-slot="scope">
                  <span>{{
                    formatServiceValidTime(
                      scope.row.serviceStartTime,
                      scope.row.serviceEndTime,
                      scope.row.serviceQuantityUnit
                    )
                  }}</span>
                </template>
              </el-table-column>
              <!--              <el-table-column-->
              <!--                :label="$t('modules.contract.service_expire_time')"-->
              <!--                -->
              <!--              >-->
              <!--                <template v-slot="scope">-->
              <!--                  <span>{{ scope.row.serviceEndTime ? formatToMonth(parseInt(scope.row.serviceEndTime)):'-' }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <!--              <el-table-column-->
              <!--                :label="$t('modules.contract.unit_price')"-->
              <!--                -->
              <!--              >-->
              <!--                <template v-slot="scope">-->
              <!--                  <el-tooltip-->
              <!--                    v-if="scope.row.price"-->
              <!--                    class="item"-->
              <!--                    effect="dark"-->
              <!--                    :content="scope.row.price + ' '-->
              <!--                      + $t('flycare.billing_service.' + scope.row.billingServiceCode + '.price_unit')"-->
              <!--                    placement="top-start">-->
              <!--                    <span>{{ '$' + Number(scope.row.price).toLocaleString() }}</span>-->
              <!--                  </el-tooltip>-->
              <!--                  <span v-else>{{ '-' }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <!--              <el-table-column prop="freeNum" :label="$t('modules.contract.free_count')" width="130px" >-->
              <!--                <template v-slot="scope">-->
              <!--                  <p>{{ scope.row.freeNum ? Number(scope.row.freeNum).toLocaleString() : '-' }}</p>-->
              <!--                  <p v-if="scope.row.freeExpireTime">-->
              <!--                    <el-tag size="small" type="warning">{{ 'Expire:' + formatToMonth(scope.row.freeExpireTime) }}</el-tag>-->
              <!--                  </p>-->
              <!--                </template>-->
              <!--              </el-table-column>-->

              <el-table-column :label="$t('common.status')" prop="status" width="100px">
                <template v-slot="scope">
                  <div class="montyly-resource-settlement-tooltip">
                    <el-tooltip v-if="scope.row.status == 0" placement="top-start">
                      <template #content>
                        <div style="max-width: 300px; line-height: 160%">
                          <span
                            >{{ $t("modules.contract.invalid_time") }}:
                            {{ scope.row.invalidTime }}</span
                          ><br />
                          <span
                            >{{ $t("modules.contract.invalid_person") }}:
                            {{ scope.row.invalidUserName }}</span
                          >
                        </div></template
                      >
                      <div>
                        <el-tag
                          size="small"
                          :type="scope.row.status == '1' ? 'success' : 'danger'"
                          disable-transitions
                        >
                          {{ formatContractModuleStatus(scope.row.status) }}
                        </el-tag>
                      </div>
                    </el-tooltip>
                    <div v-else>
                      <el-tag
                        size="small"
                        :type="formatStatusType(scope.row.status)"
                        disable-transitions
                      >
                        {{ formatContractModuleStatus(scope.row.status) }}
                      </el-tag>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="remark" :label="$t('common.remark')" />
              <el-table-column
                :label="$t('common.creation_time')"
                prop="creDate"
                width="120px"
              >
                <template v-slot="scope">
                  <div>
                    <el-tooltip placement="top-start">
                      <template #content>
                        <div style="max-width: 300px; line-height: 160%">
                          <span>{{ scope.row.creTime }}</span
                          ><br /></div
                      ></template>
                      <div>
                        {{ scope.row.creDate }}
                      </div>
                    </el-tooltip>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                v-if="contractData.status === 1"
                :label="$t('modules.contract.operate')"
                width="90px"
              >
                <template v-slot="scope">
                  <div v-if="scope.row.status === 1">
                    <el-button
                      v-permission="{ permission: '10401000.MANAGE' }"
                      type="text"
                      size="small"
                      @click="invalidModule(scope.row.contractModuleId)"
                      >{{ $t("common.invalid") }}</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  checkContract,
  getDefaultEmail,
  invalidContract,
  invalidModuleContract,
  validContract,
} from "@/api/contract";
import { toTime, toTenYMD } from "@/utils/index";
import { isAuth } from "@/utils";

export default {
  components: {},
  data() {
    return {
      loading: false,
      addModuleVisible: false,
      genStatementVisible: false,
      genStatementFailedVisible: false,
      fixedEmail: "",
      moduleForm: {
        platCode: "",
        moduleCode: "",
        statisticMethod: "",
        billingCycle: "1",
        currency: "1",
        price: "",
        freeNum: "",
        effectiveDate: "",
        expiringDate: "",
        paymentMethod: "",
      },
      moduleData: [],
      contractDate: [],
      contractData: {
        creUserId: "123",
        characterCode: "",
        keyId: "",
        contractNum: "",
        effectiveDate: "",
        expiringDate: "",
        remark: "",
        email: "",
        moduleList: [],
      },
      invalidCount: 0,
      multipleSelection: "",
      userName: "",
    };
  },
  mounted() {
    this.getContractDetail();
    this.getDefaultNotifyEmail();
  },
  methods: {
    isAuth,
    // 返回
    back() {
      this.$router.back();
    },
    formatServiceUnit(unitCode) {
      if (unitCode) {
        return this.$t("flycare.billing_service_unit." + unitCode);
      } else {
        return "USD";
      }
    },
    // 合同一键失效
    ContractInvalid() {
      const uuid = this.$route.query.contractUuid;
      // 加个确认
      this.$confirm(this.$t("tip_content.invalid_contract"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          invalidContract(uuid)
            .then((res) => {
              this.getContractDetail();
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch((e) => {});
    },
    // 合同一键生效
    ContractValid() {
      const uuid = this.$route.query.contractUuid;
      // 加个确认
      this.$confirm(this.$t("tip_content.valid_contract"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          validContract(uuid)
            .then((res) => {
              this.getContractDetail();
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch((e) => {});
    },
    formatToMonth(timestamp) {
      const ymd = toTenYMD(timestamp);
      return ymd;
    },
    formatStatusType(status) {
      if (status === 1) {
        return "success";
      }
      if (status === 0) {
        return "danger";
      }
      if (status === -1) {
        return "info";
      }
      return "success";
    },
    formatContractModuleStatus(status) {
      if (status === 1) {
        return this.$t("modules.contract.status_option[1].label");
      }
      if (status === 0) {
        return this.$t("modules.contract.status_option[0].label");
      }
      if (status === -1) {
        return this.$t("modules.contract.status_option[2].label");
      }
    },
    formatServiceValidTime(serviceStartTime, serviceEndTime, serviceQuantityUnit) {
      if (!serviceStartTime && !serviceEndMonth) return "-";
      let serviceStartMonth = "*";
      let serviceEndMonth = "*";
      if (serviceStartTime) {
        serviceStartMonth = this.formatToMonth(serviceStartTime);
        if (serviceQuantityUnit === "SINGLE") {
          return serviceStartMonth;
        }
      }
      if (serviceEndTime) {
        serviceEndMonth = this.formatToMonth(serviceEndTime);
      }
      return serviceStartMonth + " ~ " + serviceEndMonth;
    },
    handleCommand(command, row) {
      if (command === "invalid") {
        this.invalidModule(row.contractModuleId);
      }
      if (command === "generate") {
        this.generateCosts(row);
      }
    },
    generateCosts(contractModule) {
      this.openGenerateStatement(contractModule);
    },
    // 获取合同详情
    getContractDetail() {
      this.loading = true;
      checkContract(this.$route.query.contractUuid)
        .then((res) => {
          console.log(res);
          this.userName = res.userName;
          this.moduleData = res.moduleList;
          for (let i = 0; i < this.moduleData.length; i++) {
            this.moduleData[i].creDate = toTenYMD(this.moduleData[i].creTime);
            this.moduleData[i].creTime = toTime(this.moduleData[i].creTime);
            this.moduleData[i].invalidTime = toTime(
              parseInt(this.moduleData[i].invalidTime)
            );
            this.moduleData[i].updateTime = toTime(
              parseInt(this.moduleData[i].updateTime)
            );
          }
          this.contractData = res;
          this.loading = false;
        })
        .catch((err) => {
          this.$message.error(err.message);
          this.loading = false;
        });
    },
    getDefaultNotifyEmail() {
      getDefaultEmail().then((res) => {
        this.fixedEmail = "";
        if (res.length > 0) {
          res.forEach((email) => {
            this.fixedEmail += email + ";";
          });
          this.fixedEmail = this.fixedEmail.substring(0, this.fixedEmail.length - 1);
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.invalidCount = val.length;
    },
    // 合同模块单个失效
    invalidModule(ModuleId) {
      // 加个确认
      this.$confirm(this.$t("tip_content.invalid_module"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          const array = [];
          array.push(ModuleId);
          invalidModuleContract(array)
            .then((res) => {
              this.getContractDetail();
              console.log(res);
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch((e) => {});
    },
    // 模块批量失效
    invalidModules() {
      // 加个确认
      this.$confirm(this.$t("tip_content.invalid_select_module"), "", {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning",
      })
        .then(() => {
          const array = [];
          for (let i = 0; i < this.multipleSelection.length; i++) {
            array.push(this.multipleSelection[i].contractModuleId);
          }
          invalidModuleContract(array)
            .then((res) => {
              this.getContractDetail();
              console.log(res);
            })
            .catch((err) => {
              this.$message.error(err.message);
            });
        })
        .catch((e) => {});
    },
    goToDetail() {
      this.$router.push({
        path: "/service-management/contract/edit",
        query: { contractUuid: this.$route.query.contractUuid },
      });
    },
    // 批量限制
    selected(row, index) {
      if (row.status === 1) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.box {
  margin: 0.2em 0.5em;
}

.title-logo {
  font-size: 0.8em;
  margin-left: 0px;
  color: #909399;
}

.box-header {
  font-weight: bold;
  font-size: 1.8em;
  color: #12263f;
}

.itemTime {
  display: inline-block;
  width: 300px;
}

.buttomItem {
  margin-top: 40px;
}

.theFirst {
  margin: 10px 6px;
  width: 500px;
}

.textLayout {
  display: flex;
  justify-content: center;
  align-items: center;
}

.selectSpan {
  display: inline-block;
  padding-left: 16px;
  font-size: 14px;
  font-weight: 500;
  line-height: 50px;
}

.selectBorder {
  display: inline-block;
  width: 20px;
  height: 30px;
  vertical-align: middle;
  border-right: 1px solid black;
}

.item {
  margin-bottom: 20px;
}

.selectColumn {
  width: 100%;
  height: 50px;
  margin-left: 0px;
  color: #c2c7ce;
  background-color: #edf2f9;

  &.active {
    color: #12263f;

    .buttonInvalid {
      color: white;
      background-color: #2569c3;
      border: 1px solid #2569c3;
    }
  }

  .buttonInvalid {
    color: #c2c7ce;
    background-color: #dde1e8;
    border: 1px solid #dde1e8;
  }
}

.flexContract {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
</style>
